<?php
/**
 * Created by PhpStorm.
  * User: longli
 * VX: isa1589518286
 * Date: 2020/04/14
 * Time: 15:47
 * @link http://www.lmterp.cn
 */

namespace app\common\library;

use app\common\model\Orders;

class OrderHelp
{
    /**
     * 生成内部唯一订单号
     * @param string $platformCode 平台编码
     * @param string $num 第几个订单, 1-9, a-z 可代表的订单数，共35个
     * @return string
     * @date 2020/04/14
     * @author longli
     */
    public static function generatorOrderSn($platformCode, $num = '1')
    {
        $platformCode = strtoupper($platformCode);
        return "{$platformCode}{$num}-" . date('YmdHis') . mt_rand(10000, 99999);
    }

    /**
     * 通过当前内部订单号生成下一个内部订单号
     * @param string $orderSn 内部订单号
     * @return string|bool 下一个内部订单号, false 生成失败
     * @date 2021/08/12
     * @author longli
     */
    public static function generateNextOrderSn($orderSn)
    {
        $sn = self::parseOrderSn($orderSn);
        $curr = $sn['n'];
        if(!$curr) return false;
        if(!is_numeric($curr)) $curr = ord(strtoupper($curr));
        if($curr >= 90) return false;
        if($curr > 8 && $curr < 64) $curr = 64;
        $num = ++$curr > 9 ? chr($curr) : $curr;
        $sn = "{$sn['c']}{$num}-{$sn['t']}";
        if(Orders::hasSn($sn)) $sn = self::generateNextOrderSn($sn);
        return $sn;
    }

    /**
     * 解析内部订单号
     * @param string $orderSn 内部订单号
     * @return array
     * @date 2021/08/12
     * @author longli
     */
    public static function parseOrderSn($orderSn)
    {
        $array = explode('-', $orderSn);
        return [
            'c' => substr($array[0], 0, -1),
            'n' => substr($array[0], -1),
            't' => $array[1],
        ];
    }

    /**
     * 生成 zip 压缩包
     * @param string|string[] $files 文件路径
     * @return bool|string
     * @date 2020/12/12
     * @author longli
     */
    public static function compressFile($files)
    {
        if(empty($files)) return false;
        if(!is_array($files)) $files = [$files];
        $emptyFile = true;
        // 检查文件是否有文件
        foreach($files as $file)
        {
            if(is_file($file))
            {
                $emptyFile = false;
                break;
            }
        }
        if($emptyFile) return false;
        $path = \Env::get('root_path') . "./public/attachment/compress";
        if(!is_dir($path)) mkdir($path, 0777, true);
        $filename = date("YmdHis") . ".zip";
        $zip = new \ZipArchive();
        $zip->open("$path/$filename", \ZipArchive::CREATE);
        foreach($files as $file)
        {
            if(!is_file($file)) continue;
            //向压缩包中添加文件
            $zip->addFile($file, basename($file));
        }
        //关闭压缩包
        $zip->close();
        return \app\common\service\BaseService::hiddenRootPath("$path/$filename");
    }
}